package cn.cqs.util;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;

/**
 * 封装一个登录
 */
public class ShiroUtil {

 public static Subject login(String config,String username,String password){
//     1.获取SecurityManager工厂
     Factory<SecurityManager> securityManagerFactory = new IniSecurityManagerFactory(config);
//        2.获取SecurityManger实例
     SecurityManager instance = securityManagerFactory.getInstance();
//        3.(获取之前将委托给SecurityManger)
     SecurityUtils.setSecurityManager(instance);
     Subject subject = SecurityUtils.getSubject();
//        4.模拟用户登录
     UsernamePasswordToken token = new UsernamePasswordToken(username,password);
     try {
         subject.login(token);
         return subject;
     } catch (AuthenticationException e) {
         e.printStackTrace();
     }
     return  null;
 }
}
